package edu.gyc.hiseckill.controller;


import edu.gyc.hiseckill.error.BusinessErrorEnum;
import edu.gyc.hiseckill.error.BusinessException;
import edu.gyc.hiseckill.model.CommonReturnType;
import edu.gyc.hiseckill.model.UserInfo;
import edu.gyc.hiseckill.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ls
 * @since 2020-01-20
 */
@RestController
@Slf4j
@RequestMapping("/user")
@CrossOrigin(allowCredentials="true",allowedHeaders = "*") //前后端分离部署时，服务器端要配置@CrossOrigin(allowCredentials="true",allowedHeaders = "*") // //前后端分离部署时，服务器端要配置

public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @RequestMapping("/getuser")

    public Object getuser(@RequestParam(defaultValue = "1") Integer id) throws BusinessException {
        UserInfo userInfo = userInfoService.getById(id);
        if (userInfo == null) {

        throw new BusinessException(BusinessErrorEnum.USER_NOT_EXIST);
        }
        return CommonReturnType.create(userInfo);
    }
@PostMapping("/getotp")

    public Object getOtp(String mobile) {
    Random random = new Random();
    int n = random.nextInt(99999);
    n+=10000;
    String otpCode = String.valueOf(n);

    //将OTP验证码对应用户的手机号，用session关联
        httpServletRequest.getSession().setAttribute(mobile,otpCode);
        log.info("otp: "+mobile+":"+otpCode);
    return CommonReturnType.create("TestOtp");
    }

    @PostMapping("/reg")

    public Object reg(@Validated UserInfo userInfo, BindingResult bindingResult) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
        if(bindingResult.hasFieldErrors()){
            throw new BusinessException(BusinessErrorEnum.PARAMETER_VALIDATION_ERROR);
        }

        String otpCode = (String) httpServletRequest.getSession().getAttribute(userInfo.getMobile());
        if (StringUtils.isBlank(otpCode)) {
            throw new BusinessException(BusinessErrorEnum.PARAMETER_VALIDATION_ERROR,"验证码不能为空");
        }

        if (otpCode.equals(userInfo.getOtp())) {
            userInfo.setRegMode("手机");
            //只支持16位密码
           // userInfo.setPassword(MD5Encoder.encode(userInfo.getPassword().getBytes()));
            userInfo.setPassword(EncodeByMd5(userInfo.getPassword()));
            if (userInfoService.save(userInfo)) {
                return CommonReturnType.create("注册成功");
            }
        }

        return CommonReturnType.create("注册失败");
    }


    @PostMapping("/login")

    public Object login(UserInfo userInfo) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {


        UserInfo user =userInfoService.lambdaQuery().eq(UserInfo::getMobile,userInfo.getMobile()).one();
        if (user == null) {
            throw new BusinessException(BusinessErrorEnum.LOGIN_FAIL);
        }

        String inputPassword = EncodeByMd5(userInfo.getPassword());
        if (!StringUtils.equals(user.getPassword(), inputPassword)) {
            throw new BusinessException(BusinessErrorEnum.LOGIN_FAIL);
        }

         httpServletRequest.getSession().setAttribute("LOGIN_USER",user);
         httpServletRequest.getSession().setAttribute("IS_LOGIN",true);
        return CommonReturnType.create(user.getUsername(),"success");
    }

    private static String EncodeByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        BASE64Encoder base64Encoder=new BASE64Encoder();
        String newstr = base64Encoder.encode(md5.digest(str.getBytes("utf-8")));
        return newstr;
    }
}

